//引入全局的app.js文件对象
const app = getApp();
Page({
        data: {
                replyVisibility: [], // 控制每个问题的回复展开状态
                courseList1: [],
                courseType: '',
                consults: '',
                Level: '',
                consultLevel: '',
             
                courseMarkList: [],
                courseLenth: '',
                courseTalkList: [],
                courseReplyList: [],
                replyUserList: [],
                userList: '',
                courseRepliesMap: {},

                courseId: '',
                id: 0,
                price: '',

                userList: [],
                url: '',

                value: '',

                isReplyVisible: false,
                currentUserInfo: '',
                showCertificate: false, // 弹窗控制状态
        },
        // 显示证书弹窗
        showCertificatePopup() {
                console.log('触发证书弹窗');
                this.setData({
                        showCertificate: true
                });
        },

        // 关闭证书弹窗
        hideCertificatePopup() {
                this.setData({
                        showCertificate: false
                });
        },
        toYuYue(e) {
                console.log(e.currentTarget.dataset);
                const sendData = {
                        data: {
                                name: e.currentTarget.dataset.consultname,
                                id: e.currentTarget.dataset.consultid
                        }
                };
                wx.navigateTo({
                        url: '/pages/zixun/zixunnew/zixunnew',
                        success: function (res) {
                                // 通过eventChannel向被打开页面传送数据
                                res.eventChannel.emit('acceptDataFromOpenerPage', sendData)
                        },
                        fail: function (err) {
                                console.error("跳转失败:", err);
                        }
                })
        },
        // 跳转咨询师详情页面
        toConsultDetails(e) {
                console.log(e.currentTarget.dataset.detail);
                wx.navigateTo({
                        url: '/pages/zixun/Details/details',
                        success: function (res) {
                                // 通过eventChannel向被打开页面传送数据
                                res.eventChannel.emit('acceptDataFromOpenerPage', {
                                        data: e.currentTarget.dataset.detail
                                })
                        },
                        fail: function (err) {
                                console.error("跳转失败:", err);
                        }
                })
        },
        formatTime(timeString) {
                if (!timeString) return '';
                const date = new Date(timeString);
                return `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;
        },
        toggleReply(e) {
                const index = e.currentTarget.dataset.index;
                const visibility = `replyVisibility[${index}]`;
                this.setData({
                        [visibility]: !this.data.replyVisibility[index]
                });
        },
        onLoad(options) {
                let user = wx.getStorageSync('UserInfo')
                let that = this;
                //读取全局的url赋值给当前的url网址，便于整个页面的使用
                this.setData({
                        url: app.globalData.URL,
                        currentUserInfo: user

                }, () => {
                        // 初始化数值回调函数

                })
                // console.log(that.data.currentUserInfo);
                const eventChannel = this.getOpenerEventChannel()
                // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
                eventChannel.on('onlineDetail', function (data) {
                        that.setData({
                                id: data.id
                        })
                    
                        // 获得列表
                        that.getcourselist()
                //      获得课程评价
                            that.getcoursemark()
                              
                })
        },
//  课程评价
getcoursemark(){
        let that=this
        wx.request({
                url: that.data.url + `/courseMark/selectAll`,
                data: {
                        pageSize: 10
                },
                success(resp) {
                        console.log("得到评价",resp.data.data.list);
                 
                        that.setData({
                                courseMarkList: resp.data.data.list,
                                courseLength: resp.data.data.list.length
                        },()=>{
                                const currentDateTime =that.getCurrentDateTime();
                                console.log("当前时间",currentDateTime);
                                let aa= resp.data.data.list;
that.data.courseMarkList.forEach((item,index)=>{
        const timeStr1 = item.createTime;
const timeStr2 = currentDateTime;
const result = that.calculateTimeDifference(timeStr1, timeStr2);
console.log('相差的时间:', result);
aa[index].createTime=result
})
that.setData({
        courseMarkList:aa
})
                        })
                }
        })
},
// 计算时间差值
 calculateTimeDifference(dateStr1, dateStr2) {
        // 将日期字符串转换为 Date 对象
        const date1 = new Date(dateStr1);
        const date2 = new Date(dateStr2);
    
        // 计算两个日期的时间戳差值（以毫秒为单位）
        const diffMs = Math.abs(date2 - date1);
    
        // 定义不同时间单位对应的毫秒数
        const oneHourMs = 1000 * 60 * 60;
        const oneDayMs = oneHourMs * 24;
        // 粗略计算，一个月按 30 天算
        const oneMonthMs = oneDayMs * 30; 
        // 粗略计算，一年按 365 天算
        const oneYearMs = oneDayMs * 365; 
    
        if (diffMs < oneDayMs) {
            // 差值小于一天，按小时计算
            const diffHours = Math.floor(diffMs / oneHourMs);
            return `${diffHours} 小时`;
        } else if (diffMs < oneMonthMs) {
            // 差值小于一个月，按天计算
            const diffDays = Math.floor(diffMs / oneDayMs);
            return `${diffDays} 天`;
        } else if (diffMs < oneYearMs) {
            // 差值小于一年，按月计算
            const diffMonths = Math.floor(diffMs / oneMonthMs);
            return `${diffMonths} 个月`;
        } else {
            // 差值大于一年，按年计算
            const diffYears = Math.floor(diffMs / oneYearMs);
            return `${diffYears} 年`;
        }
    },
    
    

   

// 获取当前时间
 getCurrentDateTime() {
        const now = new Date();
        // 获取年份
        const year = now.getFullYear();
        // 获取月份，注意 getMonth() 返回值是 0 - 11，所以要加 1
        const month = String(now.getMonth() + 1).padStart(2, '0');
        // 获取日期
        const day = String(now.getDate()).padStart(2, '0');
        // 获取小时
        const hours = String(now.getHours()).padStart(2, '0');
        // 获取分钟
        const minutes = String(now.getMinutes()).padStart(2, '0');
        // 获取秒数
        const seconds = String(now.getSeconds()).padStart(2, '0');
    
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
    ,
    // 调用函数获取当前日期和时间
 
        // 课程列表
        getcourselist() {
                let that =this
                wx.request({
                         // ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss
                        url: that.data.url + `/course/`+that.data.id,
                        method:"GET",
                        success(resp) {
                                console.log("课程列表",resp.data.data);
                                that.setData({
                                                courseList1: resp.data.data,
                                                courseId: resp.data.data.id,
                                                price: resp.data.data.discountPrice,
                                                courseType:resp.data.data.courseType.name,
                                                consults:resp.data.data.consult,
                                                consultLevel:resp.data.data.consult.consultLevel
                                        }),
                                        // 课程状态
                                        that.coursestatus()

                        }
                })
        },
        // 课程状态
        coursestatus() {
                let that = this
                wx.request({
                        url: that.data.url + `/courseOrder/selectAll`,

                        data: {
                                userId: that.data.currentUserInfo.id,
                                courseId: that.data.courseId
                        },
                        success(resp) {
                                // console.log(resp.data.data.list[0].status);
                                if (resp.data.data.list[0].status == 2) {

                                        that.setData({
                                                coursePurchased: true
                                        })
                                } else {
                                        that.setData({
                                                coursePurchased: false
                                        })
                                }
                        }
                })

        },
        toggleReplyVisibility: (e) => {
                const that = this
                const index = e.currentTarget.dataset.index;
                const visibility = `isReplyVisible[${index}]`;
                that.setData({
                        [visibility]: !that.data.isReplyVisible[index]
                });
        },
        addPoints() {
                let that = this
                // 检查用户是否已登录
                if (!that.data.currentUserInfo || !that.data.currentUserInfo.id) {
                        wx.showModal({
                                title: '提示',
                                content: '您还未登录，请先登录。',
                                showCancel: true,
                                cancelText: '取消',
                                confirmText: '去登录',
                                success(res) {
                                        if (res.confirm) {
                                                wx.navigateTo({
                                                        url: '/pages/my/login/login' // 跳转到登录页面
                                                });
                                        }
                                }
                        });
                        return; // 终止后续购买流程
                }

                let userid = that.data.currentUserInfo.id

                //定义时间格式
                let now = new Date();
                let year = now.getFullYear();
                let month = String(now.getMonth() + 1).padStart(2, "0");
                let day = String(now.getDate()).padStart(2, "0");
                let hours = String(now.getHours()).padStart(2, "0");
                let minutes = String(now.getMinutes()).padStart(2, "0");
                let seconds = String(now.getSeconds()).padStart(2, "0");
                let purchaseTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

                let courseId = that.data.courseId;
                let price = that.data.price;
                wx.request({
                        url: that.data.url + `/user/selectById?id=${userid}`,
                        success(resp) {
                                // console.log(resp.data.point);
                                let addPoint = resp.data.point + 3
                                // console.log(addPoint);
                                // console.log(userid);
                                that.setData({
                                        userList: resp.data.data
                                }, () => {
                                        // console.log(addPoint);
                                        // console.log(userid);
                                        //更新用户积分
                                        wx.request({
                                                url: that.data.url + `/user/update`,
                                                method: "POST",
                                                header: {
                                                        "Content-Type": "application/json" // 确保正确的 Content-Type
                                                },
                                                data: {
                                                        User: JSON.stringify({
                                                                id: userid,
                                                                point: addPoint,

                                                        }),
                                                        pagenum: 1,
                                                        pagesize: 0
                                                },
                                                success(resp) {
                                                        // console.log(resp.data);
                                                        that.setData({
                                                                coursePurchased: true
                                                                //更新成功改变按钮显示状态
                                                        });
                                                        // 在积分更新成功后，添加购买记录      
                                                        // console.log(resp.data);
                                                        wx.request({
                                                                url: that.data.url + `/courseOrder/insert`,
                                                                method: "POST",
                                                                header: {
                                                                        "Content-Type": "application/json"
                                                                },
                                                                data: {
                                                                        userId: userid,
                                                                        courseId: courseId,
                                                                        price: price,
                                                                        purchaseTime: purchaseTime,
                                                                        status: 2
                                                                },
                                                                success(resp) {
                                                                        console.log("购买记录添加成功");
                                                                }
                                                        });
                                                }
                                        })
                                })
                        }
                })
        }
});